package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.WeekEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * 返回指定日期date为星期几
 * @author 吴峰
 * @version v1.0
 * @date 2019/12/30 16:53 
 * @since v1.0
 */
public class OperatorWeekday extends Operator {


    public OperatorWeekday(String name){
        this.name = name;
    }

    public OperatorWeekday(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }


    /**
     * 语法：WEEKDAY(date)
     * 说明：返回指定日期date为星期几
     * 例如：录入【填写日期】，通过WEEKDAY函数自动填入【星期】。
     * @param list
     * list[0] 起始时间
     * list[1] 结束时间
     * @return
     * @throws Exception
     */
    @Override
    public Object executeInner(Object[] list) throws XbbException {
        if (Objects.isNull(list)) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        Long startTime = PaasDateUtil.getInt(list[0]);
        Integer weekday = DateTimeUtil.getWeekInSomeday(startTime);
        return getWeekday(weekday);
    }

    private String getWeekday(Integer weekday) {
        WeekEnum weekEnum = WeekEnum.getByCode(weekday+1);
        if (Objects.nonNull(weekEnum)) {
            return weekEnum.getName();
        }
        return "";
    }
}
